<template>
  <div class="createPost-container">
    <el-form ref="dataForm" :model="formData" :rules="rules" class="form-container">
      <sticky :z-index="10" :class-name="'sub-navbar '+formData.status">
        <!--
        <CommentDropdown v-model="formData.comment_disabled" />
        <PlatformDropdown v-model="formData.platforms" />
        -->
        <SourceUrlDropdown v-model="formData.external_url" />
        <!--
        <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm">
          Publish
        </el-button>
        <el-button v-loading="loading" type="warning" @click="draftForm">
          Draft
        </el-button>
        -->
        <el-select v-model="formData.category_id" :placeholder="$t('placeholder.select_category')">
          <el-option v-for="item in categoryData" :key="item.id" :label="item.title" :value="item.id"/>
        </el-select>
      </sticky>

      <div class="createPost-main-container">
        <el-row>
          <el-form-item style="margin-bottom: 40px;" prop="title">
            <MDinput v-model="formData.title" :maxlength="100" name="name" required>
            {{$t('table.title')}}
            </MDinput>
          </el-form-item>
          <el-col :span="24">
            <div class="postInfo-container">
              <el-row>
                <el-col :span="8">
                  <el-form-item label-width="60px" :label="$t('table.author')" class="postInfo-container-item">
                    <el-input v-model="formData.author"/>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label-width="60px" :label="$t('table.source')" class="postInfo-container-item">
                    <el-input v-model="formData.source"/>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label-width="120px" :label="$t('table.publish_date')" class="postInfo-container-item">
                    <el-date-picker v-model="publishDate" type="date" format="yyyy-MM-dd" :placeholder="$t('placeholder.select_publish_date')" />
                  </el-form-item>
                </el-col>

              </el-row>
            </div>
          </el-col>
        </el-row>

        <el-form-item style="margin-bottom: 40px;" label-width="70px" :label="$t('table.keyword')">
          <el-input v-model="formData.keyword" :rows="1" type="textarea" class="article-textarea" autosize placeholder="Please enter keyword" />
        </el-form-item>
        <el-form-item style="margin-bottom: 40px;" label-width="70px" :label="$t('table.summary')">
          <el-input v-model="formData.description" :rows="1" type="textarea" class="article-textarea" autosize placeholder="Please enter the content" />
          <span v-show="contentShortLength" class="word-counter">{{ contentShortLength }}words</span>
        </el-form-item>

        <el-form-item prop="content" style="margin-bottom: 30px;">
          <Tinymce ref="editor" v-model="formData.content" :height="400" :category="this.$route.path.replace('/admin/', '')"/>
        </el-form-item>

        <el-form-item prop="thumb" style="margin-bottom: 30px;">
          <Upload v-model="formData.thumb" action="article/thumb"/>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>
import Http from '@/utils/http'
import Tinymce from '@/components/Tinymce'
import Upload from '@/components/Upload/SingleImage3'
import MDinput from '@/components/MDinput'
import Sticky from '@/components/Sticky' // 粘性header组件
import { validURL } from '@/utils/validate'
import Warning from './Warning'
import { CommentDropdown, PlatformDropdown, SourceUrlDropdown } from './Dropdown'

const defaultForm = {
  status: 'draft',
  title: '', // 文章题目
  content: '', // 文章内容
  description: '', // 文章摘要
  external_url: '', // 文章外链
  image_uri: '', // 文章图片
  display_time: undefined, // 前台展示时间
  id: undefined,
  platforms: ['a-platform'],
  comment_disabled: false,
  importance: 0
}

export default {
  name: 'ArticleDetail',
  components: { Tinymce, MDinput, Upload, Sticky, Warning, CommentDropdown, PlatformDropdown, SourceUrlDropdown },
  props: {
    articleID: Number,
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: rule.field + '为必传项',
          type: 'error'
        })
        callback(new Error(rule.field + '为必传项'))
      } else {
        callback()
      }
    }
    const validateSourceUri = (rule, value, callback) => {
      if (value) {
        if (validURL(value)) {
          callback()
        } else {
          this.$message({
            message: '外链url填写不正确',
            type: 'error'
          })
          callback(new Error('外链url填写不正确'))
        }
      } else {
        callback()
      }
    }
    return {
      formData: Object.assign({}, defaultForm),
      categoryData: {},
      loading: false,
      userListOptions: [],
      rules: {
        image_uri: [{ validator: validateRequire }],
        title: [{ validator: validateRequire }],
        content: [{ validator: validateRequire }],
        external_url: [{ validator: validateSourceUri, trigger: 'blur' }]
      },
      tempRoute: {}
    }
  },
  computed: {
    contentShortLength() {
      // console.log('this.formData.description ', this.formData.description)
      var len = this.formData.description ? this.formData.description.length : 0
      return len > 255 ? len+'不能够超过255' : len;
    },
    publishDate: {
      // set and get is useful when the data
      // returned by the back end api is different from the front end
      // back end return => "2013-06-25 06:59:25"
      // front end need timestamp => 1372114765000
      get() {
        var tm = this.formData.publish_date
        console.log('publish date get ', tm)
        return tm ? (+new Date(tm)) : new Date()
      },
      set(val) {
        this.formData.publish_date = new Date(val)
      }
    }
  },
  created() {
    this.getCategory()
    if (this.isEdit) {
      this.fetchData(this.articleID)
    }
    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    async getCategory() {
      const CATEGORY = await Http.get(this.api.admin_article_category_valid)
      this.categoryData = CATEGORY.data
    },
    fetchData(id) {
      Http.get(this.api.admin_article + '/' + id).then(response => {
        this.formData = response.data
        console.log('response data ', response.data)
        // just for test
        this.formData.title
        this.formData.description

        // set tagsview title
        this.setTagsViewTitle()

        // set page title
        this.setPageTitle()
      }).catch(err => {
        console.log(err)
      })
    },
    setTagsViewTitle() {
      const title = this.lang === 'zh' ? '编辑文章' : 'Edit Article'
      const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.formData.id}` })
    },
    setPageTitle() {
      const title = 'Edit Article'
      document.title = `${title} - ${this.formData.id}`
    },
    submitForm() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$notify({
            title: '成功',
            message: '发布文章成功',
            type: 'success',
            duration: 2000
          })
          this.formData.status = 'published'
          this.loading = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    draftForm() {
      if (!this.formData.content || !this.formData.title || this.formData.content.length === 0 || this.formData.title.length === 0) {
        this.$message({
          message: '请填写必要的标题和内容',
          type: 'warning'
        })
        return
      }
      this.$message({
        message: '保存成功',
        type: 'success',
        showClose: true,
        duration: 1000
      })
      this.formData.status = 'draft'
    },
    getRemoteUserList(query) {
      Http.get(this.api.admin_admin, query).then(response => {
        if (!response.data.items) {
          return
        }
        this.userListOptions = response.data.items.map(v => v.name)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea /deep/ {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
